import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/home.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_demo/other/application.dart';
import 'package:flutter_demo/widget/buttons.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'c_register.dart';

class C_LoginScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _C_LoginScreenState();
}

class _C_LoginScreenState extends State<C_LoginScreen> {

  late GlobalKey _formKey;
  late TextEditingController _accountController;
  late TextEditingController _pwdController;

  @override
  void initState() {
    _formKey = GlobalKey<FormState>();
    _accountController = TextEditingController();
    _pwdController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {

    var cAccount = Container(
      width: 280,
      margin: EdgeInsets.only(
        top: 64,
      ),
      child: TextFormField(
        controller: _accountController,
        autofocus: true,
        decoration: const InputDecoration(
          labelText: '用户名',
          hintText: '您的用户名',
          prefixIcon: Icon(
            Icons.person,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 13,
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '用户名不能为空';
          } else if (value.trim().length > 10) {
            return '用户名超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var cPassword = Container(
      width: 280,
      margin: EdgeInsets.only(
        top: 16,
      ),
      child: TextFormField(
        controller: _pwdController,
        obscureText: true,
        decoration: const InputDecoration(
          labelText: '密码',
          hintText: '您的登录密码',
          prefixIcon: Icon(
            Icons.lock,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 13,
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '密码不能为空';
          } else if (value.trim().length > 15) {
            return '密码超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var submitButton = Container(
      height: 40,
      margin: EdgeInsets.only(
        top: 50,
      ),
      child: BaseButton(
        radius: 5,
        withShadow: false,
        onTap: () {
          if ((_formKey.currentState as FormState).validate())
            validatePassed(context);
        },
        child: const Text(
          '登录',
          style: TextStyle(
            fontSize: 16,
            color: Colors.white,
          ),
        ),
      ),
    );

    var actionBar = Container(
      height: 100,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Container(
        width: 980,
        height: 100,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: Container(
                alignment: Alignment.centerLeft,
                child: Image(
                  image: NetworkImage('http://my.gxrczc.com/assets/img/logo_'
                      'login_my.jpg'),
                  width: 498,
                  height: 60,
                ),
              ),
            ),
            Image(
              image: NetworkImage('http://my.gxrczc.com/assets/img/help2.p'
                  'ng'),
              width: 140,
              height: 60,
            ),
            Image(
              image: NetworkImage('http://my.gxrczc.com/assets/img/help3.p'
                  'ng'),
              width: 206,
              height: 60,
            )
          ],
        ),
      ),
    );

    var user_login_form = Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        children: <Widget>[
          cAccount,
          cPassword,
          submitButton,
          C(20),
          Container(
            alignment: Alignment.center,
            child: InkWell(
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => C_RegisterScreen()));
              },
              child: Text(
                '单位机构注册',
                style: TextStyle(
                  color: Color(0xff303133),
                  fontSize: 14,
                ),
              ),
            ),
          )
        ],
      ),
    );

    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          actionBar,
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: NetworkImage('http://my.gxrczc.com/assets/img/login_bg1'
                      '.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  Positioned(
                    left: 850,
                    top: 125,
                    width: 340,
                    height: 420,
                    child: Container(
                      padding: EdgeInsets.all(30),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black26,
                            blurRadius: 12,
                          ),
                        ],
                      ),
                      child: user_login_form,
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _accountController.dispose();
    _pwdController.dispose();
  }

  void validatePassed(BuildContext context) async {
    Response response = await SystemApi.c_login(
        _accountController.text,
        _pwdController.text);
    var map = json.decode(response.data);
    if (response.statusCode == 200 && map['code'] == '1') {
      Fluttertoast.showToast(msg: map['msg']);
      Application.currentAccount = _accountController.text;
      Application.currentType = AccountType.company;
      Navigator.push(context,
          MaterialPageRoute(builder: (context) => HomeScreen()));
    } else if (map['code'] != '1') {
      Fluttertoast.showToast(msg: map['msg']);
    } else {
      Fluttertoast.showToast(msg: response.statusCode.toString());
    }
  }
}